package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id) {
        // 查询PO
        Category category = categoryService.getById(id);
        // PO转换DTO
        CategoryDTO categoryDTO = new CategoryDTO(category);
        // 返回
        return ResponseEntity.ok(categoryDTO);
    }

    /**
     * 根据id的集合查询分类的集合
     *
     * @param ids id集合
     * @return 分类对象集合
     */
    @GetMapping("list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids) {
        // 根据id查询
        List<Category> list = categoryService.listByIds(ids);
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据父id查询子类目的集合
     * @param pid 父类目id
     * @return 子类目的集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryOfParent(@RequestParam("pid") Long pid) {
        // 根据父id查询
        List<Category> list = categoryService.query().eq("parent_id", pid).list();
        // 转换DTO并返回
        return ResponseEntity.ok(CategoryDTO.convertEntityList(list));
    }

}
